<template>
  <el-dialog title="物资出库" :visible.sync="localVisible" @close="closeDialog">
    <el-form :model="form">
      <el-form-item label="物资编号">
        <el-input v-model="form.material_code"></el-input>
      </el-form-item>
      <el-form-item label="设备编码">
        <el-input v-model="form.device_code"></el-input>
      </el-form-item>
      <el-form-item label="领货人">
        <el-select v-model="form.dispatch_person">
          <el-option v-for="person in persons" :key="person.id" :label="person.name" :value="person.name"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { fetchPersons, dispatchMaterial } from '@/api/material';

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        material_code: '',
        device_code: '',
        dispatch_person: ''
      },
      persons: [],
      localVisible: this.visible
    };
  },
  mounted() {
    this.fetchPersons();
  },
  watch: {
    visible(val) {
      this.localVisible = val;
    },
    localVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  methods: {
    closeDialog() {
      this.localVisible = false;
      this.dialogVisible = false;
    },
    async fetchPersons() {
      const response = await fetchPersons();
      this.persons = response.data;
    },
    async handleSubmit() {
      try {
        await dispatchMaterial(this.form);
        this.visible = false;
        this.$message.success('出库成功');
      } catch (error) {
        this.$message.error('出库失败');
      }
    }
  }
};
</script>